import { getPermission } from '../../utils/permissionUtil';

Component({
  properties: {

  },
  data: {
    hasPermission: false,
    locationListener: null,
    shopLocation: null,
    location: null,
    name: '江苏路',
    range: '0m',
  },
  methods: {
    navToSearchPage() {
      console.log('navToSearchPage com')
      this.triggerEvent('navToSearchPage');
    },
    navToLocationPage() {
      getPermission({ code: 'scope.userLocation', name: '定位信息' }).then(() => {
        this.getLocation();
      })
      // this.triggerEvent('navToLocationPage');
      // this.checkLocationPermission();
    },

    // 判断用户试凑具有获取地址信息权限
    checkLocationPermission() {
      // 检查用户是否已经授权定位权限
      wx.getSetting({
        success: (res) => {
          const authStatus = res.authSetting['scope.userLocation'];
          if (authStatus) {
            this.getLocation();// 用户已经授权，直接获取定位信息
          } else {
            this.requestLocationPermission();// 用户未授权，请求授权
          }
        },
        fail: (err) => {
          // this.toastMsg('获取设置失败');
          this.triggerEvent('toastMsg', '获取设置失败');
          console.error('获取设置失败', err);
        }
      });
    },

    // 请求授权
    requestLocationPermission() {
      wx.showModal({
        title: `获取${name}失败`,
        content: `获取${name}失败，请在【右上角】-小程序【设置】项中，将【${name}】开启。`,
        confirmText: '去设置',
        confirmColor: '#FA550F',
        cancelColor: '取消',
        success(res) {
          if (res.confirm) {
            wx.openSetting({
              success(settinRes) {
                if (settinRes.authSetting[code] === true) {
                  resolve();
                } else {
                  console.warn('用户未打开权限', name, code);
                  reject();
                }
              },
            });
          } else {
            reject();
          }
        },
        fail() {
          reject();
        },
      });
      // 请求用户授权定位权限
      wx.authorize({
        scope: 'scope.userLocation',
        success: () => {
          this.getLocation();// 授权成功，获取定位信息
          // this.triggerEvent('');
        },
        fail: (err) => {
          // 授权失败，提示用户手动开启权限
          wx.showModal({
            title: '提示',
            content: '需要您的位置信息，请在设置中开启定位权限',
            showCancel: false,
            confirmText: '去设置',
            success: (res) => {
              if (res.confirm) {
                // 打开设置页面
                wx.openSetting({
                  success: (settingData) => {
                    if (settingData.authSetting['scope.userLocation']) {
                      // 用户在设置中开启了定位权限，重新获取定位信息
                      this.getLocation();
                    } else {
                      // 用户仍然拒绝授权
                      this.triggerEvent('toastMsg', '您拒绝了定位权限');
                    }
                  }
                });
              }
            }
          });
        }
      });
    },

    // 启动地理位置监听
    startLocationChangeListening() {
      console.log('startLocationChangeListening')
      // 开始监听地理位置变化
      this.setData({
        hasPermission: true
      });

      // 启动地理位置监听
      const _locationListener = (res) => {
        console.log('locationListener>>', res)
        const latitude = res.latitude;
        const longitude = res.longitude;
        const speed = res.speed;
        const accuracy = res.accuracy;
        const altitude = res.altitude;
        const verticalAccuracy = res.verticalAccuracy;
        const horizontalAccuracy = res.horizontalAccuracy;

        this.setData({
          location: {
            latitude,
            longitude,
            speed,
            accuracy,
            altitude,
            verticalAccuracy,
            horizontalAccuracy
          }
        });

        console.log('定位信息:', this.data.location);
      };

      // 设置地理位置监听
      wx.onLocationChange(_locationListener);
      wx.offLocationChange(_locationListener)

      // 保存监听器以便在页面卸载时移除
      this.setData({
        locationListener: _locationListener
      });
    },

    // 直接获取定位信息
    getLocation() {
      // this.startLocationChangeListening();
      this.getWXLocation();
    },
    getWXLocation() {
      // 获取用户的位置信息
      wx.getLocation({
        type: 'wgs84', // 返回 GPS 坐标
        success: (res) => {
          console.log('getLocation: ', res)
          const latitude = res.latitude;
          const longitude = res.longitude;
          const speed = res.speed;
          const accuracy = res.accuracy;
          const altitude = res.altitude;
          const verticalAccuracy = res.verticalAccuracy;
          const horizontalAccuracy = res.horizontalAccuracy;

          this.setData({
            location: {
              latitude,
              longitude,
              speed,
              accuracy,
              altitude,
              verticalAccuracy,
              horizontalAccuracy
            },
            hasPermission: true
          });
          console.log('定位信息:', this.data.location);
        },
        fail: (err) => {
          console.error('获取位置信息失败', err);
          this.triggerEvent('toastMsg', '获取位置信息失败');
        }
      });
    },
  }
})